package test;

import static org.junit.Assert.*;
import org.junit.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MathExerciseGeneratorTest {

    // 测试数字范围（1-99）
    @Test
    public void testNumberRange() {
        Pattern pattern = Pattern.compile("(\\d+)");
        for (int i = 0; i < 100; i++) {
            String ex = MathExerciseGenerator.generateExercise(2, MathExerciseGenerator.OpType.ALL_MIXED);
            Matcher matcher = pattern.matcher(ex);
            while (matcher.find()) {
                int num = Integer.parseInt(matcher.group());
                assertTrue(num > 0 && num < 100);
            }
        }
    }

    // 测试除法是否为整数
    @Test
    public void testDivisionIsInteger() {
        Pattern pattern = Pattern.compile("(\\d+) ÷ (\\d+)");
        for (int i = 0; i < 100; i++) {
            String ex = MathExerciseGenerator.generateExercise(2, MathExerciseGenerator.OpType.DIV);
            Matcher matcher = pattern.matcher(ex);
            assertTrue(matcher.find());
            int a = Integer.parseInt(matcher.group(1));
            int b = Integer.parseInt(matcher.group(2));
            assertEquals(0, a % b);
        }
    }

    // 测试3个数运算中间结果合法性
    @Test
    public void testThreeNumIntermediateResult() {
        Pattern pattern = Pattern.compile("(\\d+) ([+\\-×÷]) (\\d+) ([+\\-×÷]) (\\d+)");
        for (int i = 0; i < 100; i++) {
            String ex = MathExerciseGenerator.generateExercise(3, MathExerciseGenerator.OpType.ALL_MIXED);
            Matcher matcher = pattern.matcher(ex);
            assertTrue(matcher.find());
            int a = Integer.parseInt(matcher.group(1));
            int b = Integer.parseInt(matcher.group(3));
            int c = Integer.parseInt(matcher.group(5));
            char op1 = matcher.group(2).charAt(0);
            char op2 = matcher.group(4).charAt(0);

            // 验证第一步结果
            Integer step1 = calculateStep(a, b, op1);
            assertNotNull(step1);
            assertTrue(step1 > 0 && step1 < 100);

            // 验证最终结果
            Integer finalRes = calculateStep(step1, c, op2);
            assertNotNull(finalRes);
            assertTrue(finalRes > 0 && finalRes < 100);
        }
    }

    // 辅助计算方法（修复switch语法错误）
    private Integer calculateStep(int x, int y, char op) {
        switch (op) {
            case '+': 
                int resAdd = x + y; 
                return resAdd < 100 ? resAdd : null;
            case '-': 
                return x > y ? x - y : null;
            case '×': 
                int resMul = x * y; 
                return resMul < 100 ? resMul : null;
            case '÷': 
                return (y != 0 && x % y == 0) ? x / y : null;
            default: 
                return null;
        }
    }
}
